<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<script type="text/javascript">
    $(function(){
        
        var NewRealtyController = Backbone.Router.extend({
            routes: {
                "newRealtyClose": "close",
                "newRealty": "newRealty",
                "newRealtyStep2": "newRealtyStep2",
                "newRealtyStep2Back": "newRealtyStep2Back",
                "newRealtyComplete": "newRealtyComplete"
            },

            close: function () {
                newRealtyView.closeDialog();
                this.navigate("", {trigger: false, replace: true});
            },
            newRealty: function() {
                newRealtyView.openDialog();
                this.navigate("", {trigger: false, replace: true});
            },
            newRealtyStep2: function() {
                newRealtyView.nextStep();
                this.navigate("", {trigger: false, replace: true});
            },
            newRealtyStep2Back: function() {
                newRealtyView.lastStep();
                this.navigate("", {trigger: false, replace: true});
            },
            newRealtyComplete: function() {
                var self = this;
                var result = newRealtyView.save(
                // если сохраниние успешно
                function (data) {
                    console.log(data);
                    $.loadingBlock("newRealtySave", "hide");
                    self.navigate("addPhoto/" + data.realtyId, {trigger: true, replace: true});
                }, // если ошибка 
                function (data) {
                    console.log(data);
                    alert(data.message);
                    $.loadingBlock("newRealtySave", "hide");
                });
                
                if (result) {
                    newRealtyView.closeDialog();
                    this.navigate("", {trigger: false});
                    $.loadingBlock("newRealtySave", "show");
                }
                this.navigate("", {trigger: false, replace: true});
            }
        });
         
        
        NewRealtyModel = Backbone.Model.extend({
            defaults: {
                type:"APARTMENT",
                area: "",
                numberRooms: "",
                level: "",
                levelsBuilding: "",
                landArea: "",
                typeMetricLandArea: "ha",
                operation:"SALE",
                description: "",
                adress: "",
                price: ""
            },
            toDefaults: function() {
                this.set(this.defaults, {silent: true});
                this.trigger("toDefaults");
            },
            validate: function(attrs) {
                console.log(attrs);
                switch(attrs.type) {
                    case "APARTMENT":
                        if (!(attrs.area && parseFloat(attrs.area) > 0)) {
                            return {attr: "area", message: "Укажите площадь квартиры!"};
                        }
                        if (!(attrs.numberRooms && parseInt(attrs.numberRooms) > 0)) {
                            return {attr: "numberRooms", message: "Укажите количество комнат!"};
                        }
                        if (!(attrs.level && parseInt(attrs.level) > 0)) {
                            return {attr: "level", message: "Укажите этаж!"};
                        }
                        if (!(attrs.levelsBuilding && parseInt(attrs.levelsBuilding) > 0)) {
                            return {attr: "levelsBuilding", message: "Укажите сколько этажей в доме!"};
                        }
                        if (attrs.level && attrs.levelsBuilding) {
                            if (parseInt(attrs.level) > parseInt(attrs.levelsBuilding)) {
                                return {attr: "level", message: "Этаж больше чем этажей в квартире!"};
                            }
                        }
                        break;
                    case "HOUSE":
                        if (!(attrs.area && parseFloat(attrs.area) > 0)) {
                            return {attr: "area", message: "Укажите площадь дома!"};
                        }
                        if (!(attrs.numberRooms && parseInt(attrs.numberRooms) > 0)) {
                            return {attr: "numberRooms", message: "Укажите количество комнат!"};
                        }
                        if (!(attrs.landArea && parseFloat(attrs.landArea) > 0)) {
                            return {attr: "landArea", message: "Укажите площадь земли!"};
                        }
                        break;
                    case "GARAGE":
                        if (!(attrs.area && parseFloat(attrs.area) > 0)) {
                            return {attr: "area", message: "Укажите площадь гаража!"};
                        }
                        break;
                    case "OFFICE":
                        if (!(attrs.area && parseFloat(attrs.area) > 0)) {
                            return {attr: "area", message: "Укажите площадь офиса!"};
                        }
                        if (!(attrs.numberRooms && parseInt(attrs.numberRooms) > 0)) {
                            return {attr: "numberRooms", message: "Укажите количество комнат!"};
                        }
                        if (!(attrs.level && parseInt(attrs.level) > 0)) {
                            return {attr: "level", message: "Укажите этаж!"};
                        }
                        if (!(attrs.levelsBuilding && parseInt(attrs.levelsBuilding) > 0)) {
                            return {attr: "levelsBuilding", message: "Укажите сколько этажей в доме!"};
                        }
                        if (attrs.level && attrs.levelsBuilding) {
                            if (parseInt(attrs.level) > parseInt(attrs.levelsBuilding)) {
                                return {attr: "level", message: "Этаж больше чем этажей в офисе!"};
                            }
                        }
                        break;
                    case "LAND":
                        if (!(attrs.landArea && parseFloat(attrs.landArea) > 0)) {
                            return {attr: "landArea", message: "Укажите площадь земли!"};
                        }
                        break;
                }
                // Валидация адреса
                if (!(attrs.adress && attrs.adress.length > 0)) {
                    return {attr: "adress", message: "Укажите адрес!"};
                }
                if (!attrs.googleAdress || attrs.googleAdress.length == 0) {
                    return {attr: "adress", message: "Укажите адрес!"};
                }
                if (attrs.googleAdress.length > 1) {
                    return {attr: "adress", message: "Укажите правильный адрес!"};
                }          
                if (!(attrs.price && parseFloat(attrs.price) > 0)) {
                    return {attr: "price", message: "Укажите цену!"};
                }
            },
            preSave: function(data) {
                // выбираем для отпарки только один адрес
                data.googleAdress = data.googleAdress[0];
                return data;
            },
            save: function(successFunc, errorFunc) {
                var self = this;
                $.ajax({
                    type: "POST",
                    url: "<c:url value='/cabinet/api/addRealty.json' />",
                    data: JSON.stringify(self.preSave(self.toJSON())),
                    dataType : "json",
                    contentType: "application/json",
                    success: function (data, textStatus) {
                        console.log(data);
                        if (!data.error) {
                            self.trigger("saveToServer");
                            if (successFunc) {
                                successFunc(data);
                            }
                        } else {
                            console.log(data.message);
                            if (errorFunc) {
                                errorFunc(data);
                            }
                        }
                    } 
                });
            }
        });
          
        
        NewRealtyView = Backbone.View.extend({
            attrStep1: ['area', 'numbersRooms', 'level', 'levelsBuilding', 'landArea', 'typeMetricLandArea'],
            attrStep2: ['operation', 'description', 'price', 'adress'],
            initialize: function(){
                this.model.bind("toDefaults", this.render, this);
                this.model.bind("error", this.error, this);
                this.$el.find("[name=adress]").geoinput({
                    findPlace: $.proxy(this.doFindPlace, this)
                });
                this.$el.find("#mapCanvas").geomap();
            },
            render: function(){
                this._doSwitchTypeRealty(this.model.get('type'));
                this.$el.find("[name=area]").val(this.model.get('area'));
                this.$el.find("[name=numbersRooms] [value='" + this.model.get('numberRooms') + "']").prop("selected", true);
                this.$el.find("[name=level]").val(this.model.get('level'));
                this.$el.find("[name=levelsBuilding]").val(this.model.get('levelsBuilding'));
                this.$el.find("[name=landArea]").val(this.model.get('landArea'));
                this.$el.find("[name=typeMetricLandArea] [value='" + this.model.get('typeMetricLandArea') + "']").prop("selected", true);
                this.$el.find("input:radio[name=operation][value='" + this.model.get('operation') + "']").prop("checked", true);
                this.$el.find("[name=description]").val(this.model.get('description'));
                this.$el.find("[name=price]").val(this.model.get('price'));
                this.$el.find("[name=adress]").val(this.model.get('adress'));
            },
            error: function(el, messageObject) {
                if (messageObject !== true) {
                    if ($.inArray(messageObject.attr, this.attrStep1) >= 0) {
                        newRealtyController.navigate("newRealtyStep2Back", {trigger: true});
                    } else if ($.inArray(messageObject.attr, this.attrStep2) >= 0) {
                        newRealtyController.navigate("newRealtyStep2", {trigger: true});
                    } else {
                        alert("System error: dont have form attribute " + messageObject.attr);
                    }
                }
                this.errorMessage(messageObject.message);
            },
            events: {
                "click .typeRealty" : "doSelectTypeRealty"
            },
            doFindPlace: function(data) {
                if (data.length == 1) {
                    this.$el.find("#mapCanvas").geomap("setPlace", data[0]);
                    this.$el.find("#mapCanvas").geomap("addMarker", data[0]);
                }
            },
            errorMessage: function(message) {
                if (!message) {
                    $("div.errorFormRealty").hide();
                } else { 
                    $("div.errorFormRealty").html(message).show('slow');
                }
            },
            doSelectTypeRealty : function(event) {
                var target = $(event.target);
                this._doSwitchTypeRealty(target.attr("name"));
                return false;
            },
            _doSwitchTypeRealty : function(type) {
                this.$el.find("#tableFields tr").hide();
                var target = this.$el.find("[name=" + type + "]");
                target.parent().parent().find("li").removeClass("active");
                target.parent().toggleClass("active");
                this.typeRealty = type;
                switch(type) {
                    case "APARTMENT":
                        this.$el.find("#trNumberRooms").show("slow");
                        this.$el.find("#trLevel").show("slow");
                        this.$el.find("#trLevelsBuilding").show("slow");
                        this.$el.find("#trArea").show("slow");
                        break;
                    case "HOUSE":
                        this.$el.find("#trArea").show("slow");
                        this.$el.find("#trNumberRooms").show("slow");
                        this.$el.find("#trLandArea").show("slow");
                        break;
                    case "GARAGE":
                        this.$el.find("#trArea").show("slow");
                        break;
                    case "OFFICE":
                        this.$el.find("#trNumberRooms").show("slow");
                        this.$el.find("#trLevel").show("slow");
                        this.$el.find("#trLevelsBuilding").show("slow");
                        this.$el.find("#trArea").show("slow");
                        break;
                    case "LAND":
                        this.$el.find("#trLandArea").show("slow");
                        break;
                }
            },
            openDialog : function () {
                this.errorMessage();
                this.$el.modal('show');
                this.model.toDefaults();
            },
            closeDialog : function() {
                this.$el.modal("hide");
                this.lastStep();
            },
            save : function(successFunc, errorFunc) {
                this.errorMessage();
                console.log($("[name=adress]").geoinput("getPlaces"));
                var result = this.model.set({
                    type: this.typeRealty,
                    area: this.$el.find("[name=area]").val().replace(/ /g, ''),
                    numberRooms: this.$el.find("[name=numbersRooms]").val().trim(),
                    level: this.$el.find("[name=level]").val().trim(),
                    levelsBuilding: this.$el.find("[name=levelsBuilding]").val().trim(),
                    landArea: this.$el.find("[name=landArea]").val().replace(/ /g, ''),
                    typeMetricLandArea: this.$el.find("[name=typeMetricLandArea]").val(),
                    operation: this.$el.find("[name=operation]").val(),
                    description: this.$el.find("[name=description]").val().trim(),
                    adress: this.$el.find("[name=adress]").val().trim(),
                    googleAdress: this.$el.find("[name=adress]").geoinput("getPlaces"),
                    price: this.$el.find("[name=price]").val().replace(/ /g, '')
                });
                if (result !== false) {
                    this.model.save(successFunc, errorFunc);
                    return true;
                }
                return false;
            },
            nextStep : function() {
                this.$el.find("#formAddAnnouncementStep1").hide();
                this.$el.find("#formAddAnnouncementStep2").show();
                this.$el.find("[name=nextStep]").hide();
                this.$el.find("[name=lastStep]").show();
                this.$el.find("[name=complete]").show();
                return false;
            },
            lastStep : function() {
                this.$el.find("#formAddAnnouncementStep1").show();
                this.$el.find("#formAddAnnouncementStep2").hide();
                this.$el.find("[name=nextStep]").show();
                this.$el.find("[name=lastStep]").hide();
                this.$el.find("[name=complete]").hide();
            }
        });
        
        newRealtyController = new NewRealtyController();
        newRealtyModel = new NewRealtyModel();
        newRealtyView = new NewRealtyView({ el: "#formAddAnnouncement", model: newRealtyModel, controller: newRealtyController });
    });
</script>

<div id="formAddAnnouncement" class="modal hide fade" style="width:600px">
    <div class="modal-header">
        <a class="close" href="#newRealtyClose">&times;</a>
        <h3>Добавить недвижимость</h3>
    </div>
    <div class="modal-body">
        <div id="formAddAnnouncementStep1">
                <ul class="breadcrumb">
                    <li class="active">Недвижимость</li>
                </ul>
                <div class="errorFormRealty alert alert-error">
                </div>
                <ul id="type_realty" class="nav nav-tabs">
                    <li class="active">
                        <a href="#" name="APARTMENT" class="typeRealty">Квартира</a>
                    </li>
                    <li>
                        <a href="#" name="HOUSE" class="typeRealty">Дом</a>
                    </li>
                    <li>
                        <a href="#" name="GARAGE" class="typeRealty">Гараж</a>
                    </li>
                    <li>
                        <a href="#" name="OFFICE" class="typeRealty">Офис</a>
                    </li>
                    <li> 
                        <a href="#" name="LAND" class="typeRealty">Земля</a>
                    </li>
                </ul>
                <table id="tableFields">
                    <tr id="trArea">
                        <td>Полная площадь</td>
                        <td><input type="text" class="span2" name="area"/>кв. м.</td>
                    </tr>
                    <tr id="trNumberRooms">
                        <td>Количество комнат</td>
                        <td>
                            <select class="span2" name="numbersRooms">
                                <option value="1">1</option>
                                <option value="2">2</option>
                                <option value="3">3</option>
                                <option value="5">4</option>
                                <option value="5">5</option>
                                <option value="6">6</option>
                                <option value="7">7</option>
                                <option value="more">8 и более</option>
                            </select>
                        </td>
                    </tr>
                    <tr id="trLevel">
                        <td>Этаж</td>
                        <td><input type="text" class="span2" name="level"/></td>
                    </tr>
                    <tr id="trLevelsBuilding">
                        <td>Этажей в доме</td>
                        <td><input type="text" class="span2" name="levelsBuilding"/></td>
                    </tr>
                    <tr id="trLandArea">
                        <td>Площадь земли</td>
                        <td>
                            <input type="text" class="span2" name="landArea"/>
                            <select class="span2" name="typeMetricLandArea">
                                <option value="m2">кв. м.</option>
                                <option value="ha">га</option>
                                <option value="100m2">100 кв. м.</option>
                            </select>
                        </td>
                    </tr>
                </table>
                </div>


        <div id="formAddAnnouncementStep2" style="display:none">
            <ul class="breadcrumb">
                <li><a href="#newRealtyStep2Back">Информация</a> <span class="divider">/</span></li>
                <li class="active">Объявление</li>
            </ul>
            <div class="errorFormRealty alert alert-error">
            </div>
            <table>
                <tr>
                    <td>
                        <label class="checkbox inline">
                            <input type="radio" value="SALE" name="operation"> Для продажи
                        </label>
                        <label class="checkbox inline">
                            <input type="radio" value="RENT" name="operation"> Для аренды
                        </label>
                    </td>
                    <td rowspan="3">
                        <input autocomplete="off" type="text" style="width: 350px;" placeholder="Адрес" name="adress"/>
                        <div style="padding:5px;">
                            <div id="mapCanvas" style="width:300px; height:300px;"></div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td><textarea rows="3" placeholder="Описание" name="description"></textarea></td>
                </tr>
                <tr>
                    <td>
                        <div class="input-prepend input-append">
                            <span class="add-on">$</span>
                            <input class="span2" id="appendedPrependedInput" placeholder="Цена" type="text" name="price">
                            <span class="add-on">.00</span>
                        </div>
                    </td>
                </tr>
            </table>

        </div>
    </div>
    <div class="modal-footer">
        <a href="#newRealtyClose" class="btn">Отмена</a>
        <a href="#newRealtyStep2Back" class="btn btn-primary" style="display:none" name="lastStep">Назад</a>
        <a href="#newRealtyStep2" class="btn btn-primary" name="nextStep">Следующий шаг</a>
        <a href="#newRealtyComplete" class="btn btn-primary" name="complete">Готово</a>
    </div>
</div>